package us.kg.kotoriforest.springmvc.restful.advice;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import us.kg.kotoriforest.springmvc.restful.common.R;
import us.kg.kotoriforest.springmvc.restful.exception.BizException;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常处理器
 *
 * @author Kotori rotroutine@163.com
 * @since 2025/2/8
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理全局异常
    @ExceptionHandler(Exception.class)
    public R<?> handleException(Exception e) {
        return R.error();
    }

    // 处理业务逻辑异常
    @ExceptionHandler(BizException.class)
    public R<?> handleBizException(BizException e) {
        return R.error(e.getCode(), e.getMessage(), null);
    }

    // 处理参数校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errors = new HashMap<>();
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errors.put(fieldError.getField(), fieldError.getDefaultMessage());
        }

        return R.error(500, "参数校验失败", errors);
    }
}
